package com.nit.tools;

import com.google.common.base.Joiner;
import com.vladsch.flexmark.ext.tables.TablesExtension;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.parser.ParserEmulationProfile;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.data.MutableDataSet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MarkDown2HtmlTools {


    public static void main(String[] args) throws IOException {

//        String aa = MarkDown2HtmlTools.ofFile("D:\\gitee\\nit-doc\\k8s\\k8s高级实战教程三-集群篇章20230322.md");

        String aa = MarkDown2HtmlTools.ofFile("D:\\gitee\\nit-doc\\java\\nit框架说明.md");

        System.out.print( aa);
    }



    /**
     * 将本地的markdown文件，转为html文档输出
     *
     * @param path 相对地址or绝对地址 ("/" 开头)
     * @return
     * @throws IOException
     */
    public static  String ofFile(String path) throws IOException {
        return ofStream(FileReadUtil.getStreamByFileName(path));
    }


    /**
     * 将流转为html文档输出
     *
     * @param stream
     * @return
     */
    public static String ofStream(InputStream stream) throws IOException {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
            List<String> lines = bufferedReader.lines().collect(Collectors.toList());
            String content = Joiner.on("\n").join(lines);

            String html = parse(content);
            return html;
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }

    /**
     * markdown to html
     *
     * @param content markdown contents
     * @return parse html contents
     */
    private static String parse(String content) {
        MutableDataSet options = new MutableDataSet();
        options.setFrom(ParserEmulationProfile.MARKDOWN);

        // enable table parse!
        options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create()));


        Parser parser = Parser.builder(options).build();
        HtmlRenderer renderer = HtmlRenderer.builder(options).build();

        Node document = parser.parse(content);
        return renderer.render(document);
    }

}
